//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package config

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v3"
)

type MongoCfg struct {
	Url      string `yaml:"url"`
	DataBase string `yaml:"dataBase"`
}

type ExtensionServerCfg struct {
	RemoteAddr string `yaml:"remoteAddr"`
}

type RedisCfg struct {
	Addr     string `yaml:"addr"`
	PassWord string `yaml:"passWord"`
}

type DataBaseCfg struct {
	Mongo     MongoCfg           `yaml:"mongo"`
	FileStore ExtensionServerCfg `yaml:"fileStore"`
	Redis     RedisCfg           `yaml:"redis"`
}

type AdminCfg struct {
	Enable      bool   `yaml:"enable"`
	SuperUser   string `yaml:"superUser"`
	SuperPubKey string `yaml:"superPubKey"`
}

type UserCfg struct {
	CanRegister   bool `yaml:"canRegister"`
	QuickRegister bool `yaml:"quickRegister"`
}

type TraceCfg struct {
	Addr     string `yaml:"addr"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
}

type LoggingCfg struct {
	Grpc string `yaml:"grpc"`
}

type ServerConfig struct {
	GrpcPort uint16      `yaml:"grpcPort"`
	Trace    TraceCfg    `yaml:"trace"`
	Logging  LoggingCfg  `yaml:"logging"`
	DataBase DataBaseCfg `yaml:"dataBase"`
	User     UserCfg     `yaml:"user"`
	Admin    AdminCfg    `yaml:"admin"`
}

func ReadConfig(fileName string) (*ServerConfig, error) {
	data, err := os.ReadFile(fileName)
	if err != nil {
		return nil, err
	}
	servCfg := &ServerConfig{}
	err = yaml.Unmarshal(data, servCfg)
	if err != nil {
		return nil, err
	}
	if servCfg.GrpcPort == 0 {
		return nil, fmt.Errorf("miss grpcPort")
	}
	return servCfg, nil
}
